#include"drv_ADC.h"
uint16_t adc_buf[100]={0};
void drv_ADC_1_init()
{
	
	GPIO_InitTypeDef GPIO_InitStruct;
	ADC_CommonInitTypeDef ADC_CommonInitStruct;
	 ADC_InitTypeDef ADC_InitStruct;
	 DMA_InitTypeDef DMA_InitStruct;
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB,ENABLE);
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1,ENABLE);
	RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_DMA2,ENABLE);
	GPIO_InitStruct.GPIO_Pin=GPIO_Pin_1;
	GPIO_InitStruct.GPIO_Mode=GPIO_Mode_AN;//浮空输入
	GPIO_InitStruct.GPIO_PuPd=GPIO_PuPd_NOPULL;
	
	GPIO_Init(GPIOB,&GPIO_InitStruct);
	ADC_CommonInitStruct.ADC_DMAAccessMode=ADC_DMAAccessMode_Disabled;
	ADC_CommonInitStruct.ADC_Mode=ADC_Mode_Independent;
	ADC_CommonInitStruct.ADC_Prescaler=ADC_Prescaler_Div4;//84M/4=21M,不能超过36M
	ADC_CommonInitStruct.ADC_TwoSamplingDelay=ADC_TwoSamplingDelay_5Cycles;//采样周期间隔五个时钟周期
	ADC_CommonInit(&ADC_CommonInitStruct);//初始化配置公共的部分

	ADC_InitStruct.ADC_ContinuousConvMode=ENABLE;//连续转换
	ADC_InitStruct.ADC_DataAlign=ADC_DataAlign_Right;
	//ADC_InitStruct.ADC_ExternalTrigCon 
	ADC_InitStruct.ADC_ExternalTrigConvEdge=ADC_ExternalTrigConvEdge_None;//不需要外部触发
	ADC_InitStruct.ADC_NbrOfConversion=1;//通道数
	ADC_InitStruct.ADC_Resolution=ADC_Resolution_12b;
	ADC_InitStruct.ADC_ScanConvMode=DISABLE;//两个或两个以上通道才需要扫描



	
	DMA_InitStruct.DMA_BufferSize=100;
	DMA_InitStruct.DMA_Channel=DMA_Channel_0;
	DMA_InitStruct.DMA_DIR=DMA_DIR_PeripheralToMemory;
	DMA_InitStruct.DMA_FIFOMode=DMA_FIFOMode_Disable;
	DMA_InitStruct.DMA_Memory0BaseAddr=(uint32_t)adc_buf;//目标地址
	DMA_InitStruct.DMA_MemoryBurst=DMA_MemoryBurst_Single;
	DMA_InitStruct.DMA_MemoryInc=DMA_MemoryInc_Enable;
	DMA_InitStruct.DMA_MemoryDataSize=DMA_MemoryDataSize_HalfWord;
	DMA_InitStruct.DMA_Mode=DMA_Mode_Circular;
	DMA_InitStruct.DMA_PeripheralBaseAddr=(uint32_t)&ADC1->DR;
	DMA_InitStruct.DMA_PeripheralBurst=DMA_PeripheralBurst_Single;
	DMA_InitStruct.DMA_PeripheralDataSize=DMA_PeripheralDataSize_HalfWord;
	DMA_InitStruct.DMA_PeripheralInc=DMA_PeripheralInc_Disable;//外设地址不变
	DMA_InitStruct.DMA_Priority=DMA_Priority_High;//dma的优先级
	DMA_Init(DMA2_Stream0,&DMA_InitStruct);
	DMA_Cmd(DMA2_Stream0,ENABLE);
	ADC_Cmd(ADC1,ENABLE);
	ADC_RegularChannelConfig(ADC1,ADC_Channel_9,1,ADC_SampleTime_84Cycles);//设置采样规则（一个通道一个采样规则）
	ADC_DMARequestAfterLastTransferCmd(ADC1,ENABLE);//设置DMA的触发条件
	ADC_DMACmd(ADC1,ENABLE);
	ADC_SoftwareStartConv(ADC1);//触发adc开始转换
}
uint16_t drv_ac_arv()
{
	uint8_t i=0;
	uint32_t sum=0;
	for(i=0;i<100;i++)
		{
		sum=sum+adc_buf[i];
	}
	sum=sum/100;
	return (uint16_t)sum;
}

